package com.zillion.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zillion.common.exception.GlobalException;
import com.zillion.common.utils.StringUtils;
import com.zillion.common.utils.http.HttpUtils;
import com.zillion.health.domain.HealthEmployeeReserve;
import com.zillion.health.service.IHealthEmployeeReserveService;
import com.zillion.system.domain.HealthHoliday;
import com.zillion.system.service.IHealthHolidayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 定时任务调度测试
 *
 * @author zillion
 */
@Component("zlTask")
public class ZLTask {
    private static final Logger log = LoggerFactory.getLogger(ZLTask.class);

    @Autowired
    private IHealthEmployeeReserveService healthEmployeeReserveService;

    @Autowired
    private IHealthHolidayService healthHolidayService;


    public void multipleParams(String s, Boolean b, Long l, Double d, Integer i) {
        System.out.println(StringUtils.format("执行多参方法： 字符串类型{}，布尔类型{}，长整型{}，浮点型{}，整形{}", s, b, l, d, i));
    }

    public void params(String params) {
        System.out.println("执行有参方法：" + params);
    }

    public void noParams() {
        System.out.println("执行无参方法");
    }

    /**
     * 处理过期预约数据
     */
    public void handlerExpireReserveData() {
        log.info("开始处理过期的预约数据--");
        // 获取过期的预约数据
        List<Long> ids = healthEmployeeReserveService.selectEmployeeExpireReserveDataId();
        // 更改过期数据的状态为3-已过期
        if (!ids.isEmpty()) {
            healthEmployeeReserveService.updateEmployeeReserveTjStatus(ids);
            // 预约过期的数据同步到体检系统 case_case表的state = 0
            log.info("[开始同步过期预约数据到体检系统]");
            String url = "http://172.12.2.177:9300/PlugNew/healthEmployee/reserveExpire.action";
            List<HealthEmployeeReserve> expireReserveData = healthEmployeeReserveService.loadSyncExpireReserveData();
            if (!expireReserveData.isEmpty()) {
                String expireJsonStr = JSON.toJSONString(expireReserveData);
                log.info("推送的过期数据:{}", expireJsonStr);
                String sendResult = HttpUtils.sendPost(url, expireJsonStr, MediaType.APPLICATION_JSON_VALUE);
                // 处理调用结果 {"data":[1,3,4],"code":"success","msg":"同步过期预约数据成功!","success":true}
                JSONObject response = JSONObject.parseObject(sendResult);
                // 获取状态码
                String code = response.getString("code");
                if ("success".equals(code)) {// 成功处理
                    // 创建一个新的集合用来存储预约成功的id
                    ArrayList<Long> reserveIds = new ArrayList<>();
                    // 获取data
                    JSONArray data = response.getJSONArray("data");
                    // 遍历data转储为Long用于批量更改状态
                    for (int i = 0; i < data.size(); i++) {
                        Long id = data.getLong(i);
                        reserveIds.add(id);
                    }
                    // 如果回传成功就更新状态=>isPush为2
                    healthEmployeeReserveService.updateEmployeeReserveIsPushExpireData(reserveIds);
                }
            }
        } else {
            log.info("[暂无过期预约数据]");
        }
        log.info("--处理过期的预约数据结束");
    }

    /**
     * 推送预约数据到体检系统
     */
    public void pushReserveData() {
        log.info("开始推送预约数据--");
        String url = "http://172.12.2.177:9300/PlugNew/healthEmployee/employeeReserve.action";
        // 在 pushReserveData 方法中修改获取列表后的代码
        List<HealthEmployeeReserve> employeeReserves = healthEmployeeReserveService.selectEmployeeReserveToExamData();
        // 基于id字段严格去重，保持原有顺序(以下代码使用了java8新特性)
        List<HealthEmployeeReserve> uniqueEmployeeReserves = employeeReserves.stream()
                .collect(Collectors.collectingAndThen(Collectors.toMap( // 执行Map收集操作
                                HealthEmployeeReserve::getId, // 获取id字段作为map的key
                                Function.identity(), // map的value为本身的值
                                (existing, replacement) -> existing, // 如果两个key相同，则保留第一个value
                                java.util.LinkedHashMap::new), // 创建LinkedHashMap，保持原有顺序
                        map -> new ArrayList<>(map.values()))); // 把收集的map转换为 ArrayList

        if (!uniqueEmployeeReserves.isEmpty()) {
            String jsonStr = JSON.toJSONString(uniqueEmployeeReserves);
            log.info("推送的预约数据内容:{}", jsonStr);
            // 发送请求
            String sendResult = HttpUtils.sendPost(url, jsonStr, MediaType.APPLICATION_JSON_VALUE);
            // 处理调用结果 {"data":[1,3,4],"code":"success","msg":"导入预约数据成功!","success":true}
            JSONObject response = JSONObject.parseObject(sendResult);
            // 获取状态码
            String code = response.getString("code");
            if ("success".equals(code)) {// 成功处理
                // 创建一个新的集合用来存储预约成功的id
                ArrayList<Long> ids = new ArrayList<>();
                // 获取data
                JSONArray data = response.getJSONArray("data");
                // 遍历data转储为Long用于批量更改状态
                for (int i = 0; i < data.size(); i++) {
                    Long id = data.getLong(i);
                    ids.add(id);
                }
                // 如果回传成功就更新状态=>isPush为1
                healthEmployeeReserveService.updateEmployeeReserveIsPush(ids);
            }
        }else {
            log.info("[无推送的预约数据]");
        }
        log.info("--推送预约数据结束");
    }

    public void updateStatutoryHoliday(){
        log.info("开始更新法定节假日数据--");
        String url = "http://timor.tech/api/holiday/year";
        String sendResult = HttpUtils.sendGet(url);
        JSONObject response = JSONObject.parseObject(sendResult);
        if ("0".equals(response.getString("code"))) {
            JSONObject holidayObject = response.getJSONObject("holiday");
            // 遍历所有节假日
            Set<Map.Entry<String, Object>> entries = holidayObject.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                JSONObject holidayItem = (JSONObject) entry.getValue();

                // 获取节假日名称
                String holidayName = holidayItem.getString("name");
                // 是否为法定节假日
                String isHoliday = holidayItem.getString("holiday");

                // 获取日期并提取年份
                String date = holidayItem.getString("date");
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                Date parsedDate = null;
                try {
                    parsedDate = formatter.parse(date);
                    // 可以继续使用 parsedDate 进行后续操作
                } catch (ParseException e) {
                    throw new GlobalException("日期转换错误！");
                }
                String year = date.substring(0, 4); // 提取前4位作为年份

                HealthHoliday holiday = new HealthHoliday();
                holiday.setYear(year);
                holiday.setHolidayName(holidayName);
                holiday.setIsHoliday(Boolean.parseBoolean(isHoliday) ? 1 : 0);
                holiday.setHolidayDate(parsedDate);
                // 查询是否存在
                List<HealthHoliday> healthHolidays = healthHolidayService.selectHealthHolidayList(holiday);
                if (healthHolidays.size() > 0) {
                    System.out.println(year + "年节假日及调班数据已存在,无需更新！");
                    return; // 如果已存在，则直接退出当前方法
                }
                int inserted = healthHolidayService.insertHealthHoliday(holiday);
                if (inserted > 0) {
                    log.info("插入法定节假日数据成功！年份: " + year + ", 日期：" + date + ", 节假日名称: " + holidayName + ", 是否为节假日：" + isHoliday);
                } else {
                    log.info("插入法定节假日数据失败！");
                }
            }
        }
        log.info("--更新法定节假日数据结束");
    }
}
